from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Host, HostGroup, Project, Environment, UserGroup


class HostGroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = HostGroup
        fields = '__all__'


class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = '__all__'


class EnvironmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Environment
        fields = '__all__'


class HostSerializer(serializers.ModelSerializer):
    host_group_name = serializers.CharField(source='host_group.name', read_only=True)
    project_name = serializers.CharField(source='project.name', read_only=True)
    environment_name = serializers.CharField(source='environment.name', read_only=True)

    class Meta:
        model = Host
        fields = '__all__'


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'first_name', 'last_name', 'is_active', 'date_joined']


class UserGroupSerializer(serializers.ModelSerializer):
    users_detail = UserSerializer(source='users', many=True, read_only=True)
    user_count = serializers.SerializerMethodField()

    class Meta:
        model = UserGroup
        fields = '__all__'

    def get_user_count(self, obj):
        return obj.users.count()
